package com.lg.concurrent.aqs_cas.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 所有的 atomic 原子类 使用一遍 todo
 *
 cas原理： 汇编语言进行加锁 缓存行锁/总线锁

 cas aba问题：增加版本号
 */
public class Base {
    static  AtomicInteger atomicInteger = new AtomicInteger();
    static CountDownLatch countDownLatch = new CountDownLatch(10);
    //增加版本 解决aba问题
    static  AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(0, 0);

    public static void main(String[] args) {
        int count = 10;

        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                addOne();
                addOneByVersion();
                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("atomicInteger-->"+atomicInteger.get());
        System.out.println("atomicStampedReference-->"+atomicStampedReference.getReference());
    }

    static void  addOne (){
        while (true) {
            int num = atomicInteger.get();
            int calNum = num + 1;
            if(atomicInteger.compareAndSet(num, calNum))
                break;
        }
    }
    static void  addOneByVersion (){
        while (true) {
            int num = atomicStampedReference.getReference();
            int calNum = num + 1;
            if(atomicStampedReference.compareAndSet(num,calNum,atomicStampedReference.getStamp(),atomicStampedReference.getStamp()+1))
                break;
        }
    }
}
